package com.firesrc.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class EncodingFilter
 */
public class EncodingFilter implements Filter {

  /**
   * Default constructor. 
   */
  public EncodingFilter() {
    // TODO Auto-generated constructor stub
  }

  /**
   * @see Filter#destroy()
   */
  public void destroy() {
    // TODO Auto-generated method stub
  }

  /**
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpRequest.setCharacterEncoding("UTF-8");
    httpResponse.setCharacterEncoding("UTF-8");
    HttpSession session = httpRequest.getSession();
    Object currentUser = session.getAttribute("currentUser");
    String requestURI = httpRequest.getRequestURI();
    String remoteHost = httpRequest.getRemoteHost();
    System.out.println("EncodingFilter.doFilter()" + remoteHost);
    if (isNotFilter(requestURI, remoteHost)) {
      chain.doFilter(httpRequest, httpResponse);
    } else if (currentUser != null) {
      chain.doFilter(httpRequest, httpResponse);
    } else {
      forwardToLogin(httpRequest, httpResponse);
    }
  }

  private boolean isNotFilter(String requestURI, String remoteHost) {
    return requestURI.contains("loginlog.jsp") || requestURI.contains(".ico") || requestURI.contains(".png") || requestURI.contains(".bmp")
        || requestURI.contains(".jpg") || requestURI.contains(".gif") || requestURI.contains(".css") || requestURI.contains("/Log")
        || requestURI.contains("ProcessData") || remoteHost.equals("192.168.2.247") || remoteHost.equals("127.0.0.1")
        || remoteHost.equals("192.168.2.249");
  }

  private void forwardToLogin(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException, IOException {
    httpRequest.getRequestDispatcher("loginlog.jsp").forward(httpRequest, httpResponse);
  }

  /**
   * @see Filter#init(FilterConfig)
   */
  public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
  }

}
